package com.example.error.controller;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *@author 贾明祯
 *@ClassName ErrorController
 *@Date 2020/8/13 14:02
 */
@RestControllerAdvice
public class ErrorController  extends Exception{

    @ExceptionHandler(RuntimeException.class)
    public String methodArgumentNotValidHandler(HttpServletRequest request, Exception ex){
        Map<String, Object> map = new HashMap<>();
        ModelAndView mv = new ModelAndView();
        ex.printStackTrace();//打印异常信息
        // 根据不同错误获取错误信息
         if (ex instanceof UnauthorizedException) {
            map.put("code", 403);
            map.put("msg", "没有访问权限");
            map.put("data", ex.getMessage());
        }else if (ex instanceof NullPointerException) {
            map.put("code", 500);
            map.put("msg", "空指针异常");
            map.put("data", ex.getMessage());
        }else if (ex instanceof ClassCastException) {
            map.put("code", 500);
            map.put("msg", "类型转换异常");
            map.put("data", ex.getMessage());
        }else if (ex instanceof NoSuchMethodException) {
            map.put("code", 500);
            map.put("msg", "未知方法异常");
            map.put("data", ex.getMessage());
        }else if (ex instanceof IOException) {
            map.put("code", 500);
            map.put("msg", "IO异常");
            map.put("data", ex.getMessage());
        }else if (ex instanceof IndexOutOfBoundsException) {
            map.put("code", 500);
            map.put("msg", "数组越界异常");
            map.put("data", ex.getMessage());
        } else {
            String message = ex.getMessage();
            map.put("code", 500);
            //map.put("msg", "系统繁忙");
            // 开发阶段建议错误信息直接放在msg中，生产版本建议把错误信息放在data中，msg提示系统繁忙即可
            map.put("msg", message == null || message.trim().isEmpty() ? "未知异常，请联系管理员" : message);
            map.put("data", message);
        }
        return null;
    }
}
